<template>
  <a-spin class="auth-detail-wrap">
    <div class="header flex-c-sb">
      <div class="flex-c">
        <a-avatar :size="60">
          {{ billDetail.createUname }}
        </a-avatar>
        <div>
          <h3>{{ detailInfo.approvalTitle }}</h3>
          <p class="number">审批编号：{{ detailInfo.id }}</p>
        </div>
      </div>
      <a-space v-if="type == 2 && detailInfo.status == 'IN_APPROVAL'">
        <a-popconfirm @popup-visible-change="authRemark = ''" :on-before-ok="updateAuth">
          <template #content>
            <p style="margin-bottom: 10px">审核通过</p>
            <a-textarea v-model="authRemark" style="width: 300px; height: 160px" placeholder="输入审批意见" allow-clear />
          </template>
          <a-button type="primary">同意</a-button>
        </a-popconfirm>
        <a-popconfirm @popup-visible-change="authRemark = ''" :on-before-ok="updateAuthReject">
          <template #content>
            <p style="margin-bottom: 10px">审核拒绝</p>
            <a-textarea v-model="authRemark" style="width: 300px; height: 160px" placeholder="审批意见必填" allow-clear />
          </template>
          <a-button type="outline">拒绝</a-button>
        </a-popconfirm>
        <a-dropdown trigger="hover">
          <a-button>
            <template #icon>
              <icon-more />
            </template>
          </a-button>
          <template #content>
            <a-doption @click.stop="showSetAuditor = true">转交</a-doption>
            <a-doption @click.stop="showSetCarbonCopyRecipients = true">抄送</a-doption>
          </template>
        </a-dropdown>
      </a-space>
    </div>
    <div class="detail-con">
      <div class="left">
        <!-- 单据信息 -->
        <div class="title">单据信息</div>
        <a-descriptions :column="2" :data="descriptions" />
        <!-- 单据明细 -->
        <div class="table-w">
          <div style="margin-bottom: 4px">
            <span style="color: #999">合计：</span>
            <span>SKU种类 {{ billDetail.billItems && billDetail.billItems.length }}</span>
            <span style="margin-left: 15px">{{ name }}数量 {{ billDetail.totalAmt }}</span>
            <span style="margin-left: 15px">总货值 ￥{{ billDetail.totalValue }}</span>
          </div>
          <a-table class="table-singe-line show-border-table" :data="billDetail.billItems" size="mini" :pagination="false">
            <template #columns>
              <a-table-column data-index="shopName" title="店铺" :width="120" />
              <a-table-column data-index="productImg" title="图片" :width="60">
                <template #cell="{ record }">
                  <ImgPopover :src="record.productImg">
                    <template #con>
                      <a-image width="40" height="40" fit="contain" :src="record.productImg" />
                    </template>
                  </ImgPopover>
                </template>
              </a-table-column>
              <a-table-column data-index="sku" title="SKU" :width="100" />
              <a-table-column data-index="msku" title="MSKU" :width="100" />
              <a-table-column data-index="amt" title="数量" :width="60" />
              <a-table-column data-index="value" title="货值" :width="100">
                <template #cell="{ record }">
                  <p>￥{{ record.value }}</p>
                </template>
              </a-table-column>
              <a-table-column title="库存属性" :width="80">
                <template #cell="{ record }">
                  <p>{{ record.attribute == 'good' ? '良品' : '次品' }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="locationCode" title="货位" :width="80" />
            </template>
          </a-table>
        </div>
        <!-- 留言日志 -->
        <a-tabs default-active-key="1" style="margin-top: 20px">
          <a-tab-pane key="1" title="留言">
            <LeaveMessage :messageList="detailInfo.leaveMessages" :type="type" :status="detailInfo.status" :id="id" @success="getDetail()" />
          </a-tab-pane>
          <a-tab-pane key="2" title="日志">
            <AuthLog :logList="logList" />
          </a-tab-pane>
        </a-tabs>
      </div>
      <div class="right">
        <AuthNode :detail="detailInfo" />
      </div>
    </div>
    <!-- 已完成状态 -->
    <div class="status-img" v-if="detailInfo.status == 'FINISHED'">
      <a-image v-if="AuditResultIconMap[detailInfo.auditResult]" :src="AuditResultIconMap[detailInfo.auditResult]" />
    </div>
  </a-spin>
  <!-- 选择审批转交人 -->
  <ChooseUser v-if="showSetAuditor" title="转交审批" label="选择审批转交人：" :multiple="false" :isShow="showSetAuditor" :isRequired="true" :value-obj="true" @closed="showSetAuditor = false" @success="setAuditor" />
  <!-- 选择抄送人 -->
  <ChooseUser v-if="showSetCarbonCopyRecipients" labelWidth="140" title="抄送审批" label="选择抄送人(多选)：" :multiple="true" :isShow="showSetCarbonCopyRecipients" :isRequired="true" :value-obj="true" @closed="showSetCarbonCopyRecipients = false" @success="setCarbonCopyRecipients" />
</template>

<script lang="ts" setup>
  import { defineComponent, ref, onMounted, watch } from 'vue'
  import ChooseUser from '@/components/ChooseUser.vue'
  import LeaveMessage from './leaveMessage.vue'
  import AuthLog from './authLog.vue'
  import AuthNode from './authNode.vue'
  import { AuditResultIconMap } from '@/views/workFlow/types'
  import { Message } from '@arco-design/web-vue'
  import { getApprovalProcessInfo, transProcessAuditor, auditApprovalProcess, addApprovalProcessCcTo, getApprovalProcessBillInfo, findApprovalProcessLogPage } from '@/api/workFlow'
  import dayjs from 'dayjs'

  onMounted(() => {
    getDetail()
    getBillDetail()
  })

  const emit = defineEmits(['updateStatus'])
  const props = defineProps({
    id: {
      type: String,
    },
    type: {
      //审批类型 2待审批的单据才能编辑审批
      type: [String, Number],
    },
    approvalType: {
      type: String,
    },
  })
  const detailInfo = ref<any>({})
  const showSetAuditor = ref(false)
  const showSetCarbonCopyRecipients = ref(false)
  const authRemark = ref()
  const getDetailLoading = ref(false)
  const billDetail = ref<any>({})
  const logList = ref<Array<any>>([])
  const name = props.approvalType == 'OTHER_IN_ORDER_APPROVAL' ? '入库' : '出库'

  const descriptions = ref<Array<any>>([
    {
      label: '单据编号：',
      key: 'billNo',
    },
    {
      label: '创建时间：',
      key: 'gmtCreate',
    },
    {
      label: '创建人:',
      key: 'createUname',
    },
    {
      label: '目的仓库：',
      key: 'warehouseName',
    },
    {
      label: '备注：',
      key: 'remark',
      span: 2,
    },
  ])

  // 获取详情
  async function getDetail() {
    detailInfo.value = {}
    if (!props.id) return
    getDetailLoading.value = true
    const res: any = await getApprovalProcessInfo({ id: props.id })
    getDetailLoading.value = false
    detailInfo.value = res?.data || {}
    getLogList()
  }
  // 获取单据详情
  async function getBillDetail() {
    billDetail.value = {}
    if (!props.id) return
    const res: any = await getApprovalProcessBillInfo({ id: props.id })
    billDetail.value = res?.data || {}
    billDetail.value.billItems = props.approvalType == 'OTHER_IN_ORDER_APPROVAL' ? billDetail.value.otherInItems : billDetail.value.otherOutItems
    setDescriptions()
  }
  function setDescriptions() {
    descriptions.value.forEach((item, i) => {
      if (item.key == 'gmtCreate') {
        item.value = dayjs(billDetail.value.gmtCreate).format('YYYY-MM-DD HH:mm:ss')
      } else if (item.key == 'warehouseName') {
        item.value = `${billDetail.value.warehouseName}(${billDetail.value.warehouseCode})`
      } else {
        item.value = billDetail.value[item.key]
      }
    })
  }
  // 获取日志列表
  async function getLogList() {
    const res: any = await findApprovalProcessLogPage({
      billId: props.id,
      pageNum: 1,
      pageSize: 500,
    })
    logList.value = res?.data?.records || []
  }
  // 转交审批人
  async function setAuditor(user: any) {
    const res = await transProcessAuditor({
      id: detailInfo.value.id,
      newAuditUid: user.id,
      newAuditUname: user.userName,
    })
    if (res) {
      Message.success('转交成功！')
      getDetail()
      emit('updateStatus')
    }
  }
  // 抄送
  async function setCarbonCopyRecipients(users: Array<any>) {
    const res = await addApprovalProcessCcTo({
      id: detailInfo.value.id,
      newCcToIds: users.map((el: any) => el.id),
    })
    if (res) {
      Message.success('抄送成功！')
      getDetail()
    }
  }

  // 审核
  async function updateAuth() {
    let res = await requestAudit(true)
    if (!res) return false
    Message.success('已审核通过！')
    getDetail()
    emit('updateStatus')
    return true
  }
  // 拒绝
  async function updateAuthReject() {
    if (!authRemark.value) {
      Message.error('请输入拒绝原因！')
      return false
    }
    let res = await requestAudit(false)
    if (!res) return false
    Message.success('已拒绝！')
    emit('updateStatus')
    getDetail()
    return true
  }
  async function requestAudit(status: boolean) {
    let res: any = await auditApprovalProcess({
      id: detailInfo.value.id,
      message: authRemark.value,
      pass: status,
    })
    return res ? true : false
  }
  watch(
    () => props.id,
    () => {
      getDetail()
      getBillDetail()
    }
  )
</script>
<script lang="ts">
  export default defineComponent({
    name: 'OtherOutAndInAuth',
  })
</script>
<style lang="less" scoped>
  .auth-detail-wrap {
    height: 100%;
    padding: 10px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    position: relative;
    .header {
      padding-right: 30px;
      .arco-avatar {
        margin-right: 10px;
      }
      h3 {
        font-weight: bold;
        font-size: 15px;
        margin-bottom: 5px;
      }
      .number {
        font-size: 13px;
        color: #999;
      }
    }
    .detail-con {
      flex: 1;
      display: flex;
      overflow: hidden;
      .right {
        width: 300px;
        flex-shrink: 0;
        border-left: 1px solid #ddd;
        height: 100%;
        margin-left: 10px;
        padding: 0 10px;
      }
      .left {
        width: 100%;
        height: 100%;
        flex: 1;
        overflow-y: auto;
        padding-bottom: 10px;
        .title {
          margin: 20px 0;
          padding-left: 10px;
          border-left: 4px solid rgb(var(--primary-6));
        }
        .table-w {
          margin-top: 10px;
        }
      }
    }
    .status-img {
      position: absolute;
      width: 100px;
      height: 100px;
      left: 400px;
      top: 10px;
    }
  }
</style>
